package com.yanq.liancar.activity;
/*
 *  @创建者     Administrator
 *  @创建时间   2018/12/12  13:06
 *  @描述       ${TODO}
 */


import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.gyf.barlibrary.ImmersionBar;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.vondear.rxtool.RxPhotoTool;
import com.vondear.rxtool.view.RxToast;
import com.vondear.rxui.view.dialog.RxDialogChooseImage;
import com.yalantis.ucrop.UCrop;
import com.yalantis.ucrop.UCropActivity;
import com.yanq.liancar.R;
import com.yanq.liancar.activity.base.BaseToolbarActivity;
import com.yanq.liancar.bean.BaseBean;
import com.yanq.liancar.url.Config;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class SheetMetalActivity extends BaseToolbarActivity {
    @BindView(R.id.tv_1)
    TextView tv1;
    @BindView(R.id.image1)
    ImageView image1;
    @BindView(R.id.tv_upload1)
    TextView tvUpload1;
    @BindView(R.id.tv_2)
    TextView tv2;
    @BindView(R.id.image2)
    ImageView image2;
    @BindView(R.id.tv_upload2)
    TextView tvUpload2;
    @BindView(R.id.tv_kefu)
    TextView tvKefu;
    @BindView(R.id.tv_complete)
    TextView tvComplete;
    @BindView(R.id.scrollView)
    ScrollView scrollView;
    private Uri resultUri;
    private int succ;
    private List<File> fileList = new ArrayList<>();
    private Map<String, File> mFileMap = new HashMap<>();
    private String num;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sheetmetal);
        ButterKnife.bind(this);
        ImmersionBar.with(this).statusBarColor(R.color.white).statusBarDarkFont(true).init();
        mTvTitle.setText("钣金喷漆服务信息上传");

        num=getIntent().getStringExtra("oNum");

        ForegroundColorSpan colorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red));
        ForegroundColorSpan colorSpan3 = new ForegroundColorSpan(getResources().getColor(R.color.background_content));

        SpannableString spannableString = new SpannableString("图一：钣金喷漆前");
        spannableString.setSpan(colorSpan, 3, spannableString.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(colorSpan3, 0, 3, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        tv1.setText(spannableString);

        SpannableString spannableString2 = new SpannableString("图二：钣金喷漆后");
        spannableString2.setSpan(colorSpan, 3, spannableString2.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        spannableString2.setSpan(colorSpan3, 0, 3, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        tv2.setText(spannableString2);

        SpannableString spannableString1 = new SpannableString("无法拍照，请联系客服");
        ForegroundColorSpan colorSpan1 = new ForegroundColorSpan(getResources().getColor(R.color.main_color));
        spannableString1.setSpan(colorSpan1, 6, spannableString1.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        ForegroundColorSpan colorSpan4 = new ForegroundColorSpan(getResources().getColor(R.color.background_content));
        spannableString1.setSpan(colorSpan4, 0, 6, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        tvKefu.setText(spannableString1);
    }

    @OnClick({R.id.image1, R.id.tv_upload1, R.id.image2, R.id.tv_upload2, R.id.tv_kefu, R.id.tv_complete})
    public void onViewClicked(View view) {
        RxDialogChooseImage dialogChooseImage = new RxDialogChooseImage(this);
        switch (view.getId()) {
            case R.id.image1:
            case R.id.tv_upload1:
                succ=1;
                dialogChooseImage.show();
                break;
            case R.id.image2:
            case R.id.tv_upload2:
                succ=2;
                dialogChooseImage.show();
                break;
            case R.id.tv_kefu:
                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + "4008055011"));
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
                break;
            case R.id.tv_complete:
                fileList.clear();
                for (String s : mFileMap.keySet()) {
                    fileList.add(mFileMap.get(s));
                }
                if (fileList.size()==2){
                    initOkGo(num);
                }else {
                    RxToast.info("请上传完整照片");
                }
                break;
        }
    }


    private void initUCrop(Uri uri) {
        //Uri destinationUri = RxPhotoTool.createImagePathUri(this);

        SimpleDateFormat timeFormatter = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA);
        long time = System.currentTimeMillis();
        String imageName = timeFormatter.format(new Date(time));

        Uri destinationUri = Uri.fromFile(new File(getCacheDir(), imageName + ".jpeg"));

        Log.e("initUCrop: ", destinationUri + "");

        UCrop.Options options = new UCrop.Options();
        //设置裁剪图片可操作的手势
        options.setAllowedGestures(UCropActivity.SCALE, UCropActivity.ROTATE, UCropActivity.ALL);
        //设置隐藏底部容器，默认显示
        //options.setHideBottomControls(true);
        //设置toolbar颜色
        options.setToolbarColor(ActivityCompat.getColor(this, R.color.main_color));
        //设置状态栏颜色
        options.setStatusBarColor(ActivityCompat.getColor(this, R.color.main_color));

        //开始设置
        //设置最大缩放比例
        options.setMaxScaleMultiplier(5);
        //设置图片在切换比例时的动画
        options.setImageToCropBoundsAnimDuration(666);
        //设置裁剪窗口是否为椭圆
        //        options.setOvalDimmedLayer(true);
        //设置是否展示矩形裁剪框
        // options.setShowCropFrame(false);
        //设置裁剪框横竖线的宽度
        //options.setCropGridStrokeWidth(20);
        //设置裁剪框横竖线的颜色
        //options.setCropGridColor(Color.GREEN);
        //设置竖线的数量
        //options.setCropGridColumnCount(2);
        //设置横线的数量
        //options.setCropGridRowCount(1);

        UCrop.of(uri, destinationUri)
                .withAspectRatio(1, 1)
                .withMaxResultSize(1000, 1000)
                .withOptions(options)
                .start(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        initMySelfImg(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void initMySelfImg(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case RxPhotoTool.GET_IMAGE_FROM_PHONE://选择相册之后的处理
                if (resultCode == RESULT_OK) {
                    initUCrop(data.getData());
                }

                break;
            case RxPhotoTool.GET_IMAGE_BY_CAMERA://选择照相机之后的处理
                if (resultCode == RESULT_OK) {
                    initUCrop(RxPhotoTool.imageUriFromCamera);

                }

                break;
            case RxPhotoTool.CROP_IMAGE://普通裁剪后的处理
                resultUri = RxPhotoTool.cropImageUri;
                if (succ == 1) {
                    File file = roadImageView(resultUri, image1);
                    mFileMap.put("1", file);
                } else if (succ == 2){
                    File file  = roadImageView(resultUri, image2);
                    mFileMap.put("2", file);
                }
                break;

            case UCrop.REQUEST_CROP://UCrop裁剪之后的处理
                if (resultCode == RESULT_OK) {
                    resultUri = UCrop.getOutput(data);
                    if (succ == 1) {
                        File file = roadImageView(resultUri, image1);
                        mFileMap.put("1", file);
                    } else if (succ == 2){
                        File file  = roadImageView(resultUri, image2);
                        mFileMap.put("2", file);
                    }
                } else if (resultCode == UCrop.RESULT_ERROR) {
                    final Throwable cropError = UCrop.getError(data);
                }
                break;
            case UCrop.RESULT_ERROR://UCrop裁剪错误之后的处理
                final Throwable cropError = UCrop.getError(data);
                RxToast.error(cropError.getMessage());
                Log.e("asd", "initMySelfImg: " + cropError.getMessage());
                break;
            default:
                break;
        }
    }

    //从Uri中加载图片 并将其转化成File文件返回
    private File roadImageView(Uri uri, ImageView imageView) {

        Glide.with(this).
                load(uri).
                thumbnail(0.5f).
                into(imageView);

        return (new File(RxPhotoTool.getImageAbsolutePath(this, uri)));
    }


    //图片上传
    private void initOkGo(String str) {
        OkGo.<String>post(Config.s + "llc/api/serviceVoucherController/updateConsumeVoucherOrderStatus")
                .tag(this)
                .params("oNum",str)
                .addFileParams("file", fileList)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        BaseBean bean = gson.fromJson(response.body(), BaseBean.class);
                        if (bean.isIsSuccess()){
                            RxToast.success(bean.getOutputMessage());
                            finish();
                        }else {
                            RxToast.error(bean.getOutputMessage());
                        }
                    }
                });
    }
}
